package com.mmdccj.yugu.controller;

import com.mmdccj.yugu.common.Result;
import com.mmdccj.yugu.utils.AudioUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @Author: star_
 * @date: 2023-11-27 20:54
 * <p>
 * 文件上传下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    /**
     * 项目根目录
     * .e.g:  E:\code\java\yugu\yugu-music\src\main\java\com\mmdccj -> E:\code\java\yugu
     */
    private final StringBuilder BASEURL = new StringBuilder();

    {
        try {
            String[] urls = ResourceUtils.getURL("classpath:").getPath().split("/");
            /*
              TODO 打包上传到服务器需修改路径  开发为 3
             */
            for (int i = 1; i < urls.length - 3; i++) {
                BASEURL.append(urls[i]).append("/");
            }
            if (System.getProperty("os.name").toUpperCase().equals("MAC OS X")) {
                BASEURL.insert(0, "/");
            }
            BASEURL.insert(0, "/");
            log.info("当前jar包classPath位置:{}", ResourceUtils.getURL("classpath:"));
            log.info("路径{}", BASEURL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param file     文件
     * @param fileType 文件类型 e.g:music/image
     * @param format   文件具体类型 e.g:jpg/png/mp3
     * @return Result<String> 上传后的文件信息
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestBody MultipartFile file, @RequestParam String fileType, @RequestParam String format) {
        log.info("上传类型:{}", fileType);
        log.info("文件上传: {}", file);
        //原始文件名
        String path = new String();
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix;
        if (originalFilename.equals("blob")) {
            suffix = "";
        } else {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String filename = UUID.randomUUID() + suffix;
        // 判断传来的数据类型是否为Blob
        int isBlob = filename.lastIndexOf(".");
        if (isBlob == -1) {
            filename += "." + format;
        }
        log.info("isBlob{}", isBlob);
        log.info("getName{}", file.getOriginalFilename());
        try {
            String osName = System.getProperty("os.name");
            String baseURL;
            if (osName.split(" ")[0].equals("Windows")) {
                baseURL = BASEURL + "resource/";
            } else {
                baseURL = "/" + BASEURL + "resource/";
            }
            // 文件储存位置的路径
            // 获取类路径进行拼接
            switch (fileType) {
                case "music" -> path = baseURL + "music/";
                case "image" -> path = baseURL + "image/";
                default -> {
                    return Result.error("错误的文件类型");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        path = path.substring(1);
        log.info("上传路径: {}", path);
        //创建一个目录对象
        File dir = new File(path);
        //判断当前目录是否存在
        //目录不存在，需要创建
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                log.info("目录创建成功");
            }
        }
        try {
            byte[] bytes = file.getBytes();
            //文件最终完整路径
            Path fileLocation = Paths.get(path + filename);
            //将临时文件转存到指定位置
            Files.write(fileLocation, bytes);
            if (fileType.equals("music")) {
                return Result.success("成功", filename + "|" + AudioUtil.getMp3Duration(fileLocation.toFile()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.success("成功", filename);
    }

    /**
     * 下载静态资源
     *
     * @param url      文件完整名称 e.g:miku.jpg
     * @param response 请求
     */
    @GetMapping("/download")
    public void downLoad(String url, HttpServletResponse response) {
        if (url == null) {
            return;
        }
        //输入流，通过提供指定位置去读取数据
        try {
            FileInputStream fileInputStream = new FileInputStream(BASEURL + "resource/" + url);
            //输出流，通过读取到的数据输出到浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            switch (url.substring(url.length() - 3)) {
                case "mp3" -> response.setContentType("audio/mp3");
                case "jpg" -> response.setContentType("image/jpeg");
                case "png" -> response.setContentType("image/png");
            }

            //将数据通过byte字符数组进行读取
            int len;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                //刷新
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
